package com.jxauaia.contest.service;

import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.List;

@Service
@Primary
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Autowired
    private UserService userService;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("正在加载用户: {}", username);

        User user = userService.findByUsername(username);

        if (user == null) {
            logger.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        logger.info("成功加载用户: {}", username);

        // 创建权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        // 根据用户类型添加角色和权限
        if ("admin".equals(user.getUserType())) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            authorities.add(new SimpleGrantedAuthority("ROLE_USER")); // 管理员也拥有普通用户权限
            // 添加管理员特定权限
            authorities.add(new SimpleGrantedAuthority("PERMISSION_USER_MANAGE"));
            authorities.add(new SimpleGrantedAuthority("PERMISSION_CONTEST_MANAGE"));
            authorities.add(new SimpleGrantedAuthority("PERMISSION_SYSTEM_MANAGE"));
        } else {
            // 普通用户角色
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            // 添加普通用户特定权限
            authorities.add(new SimpleGrantedAuthority("PERMISSION_PROFILE_MANAGE"));
            authorities.add(new SimpleGrantedAuthority("PERMISSION_CONTEST_JOIN"));
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }

// ... 现有代码 ...
}